<template>
  <div v-permission="['production:bom:query']">
    <page-wrapper content-full-height fixed-height>
      <div class="search-wrapper">
        <j-form label-width="80px">
          <j-form-item label="商品名称">
            <a-input v-model:value.trim="searchFormData.name" allow-clear placeholder="请输入商品名称" />
          </j-form-item>
          <j-form-item label="SKU编号">
            <a-input v-model:value.trim="searchFormData.skuCode" allow-clear placeholder="请输入SKU编号" />
          </j-form-item>
        </j-form>
        <div class="search-btn">
          <a-button type="primary" @click="search" :icon="h(SearchOutlined)">查询</a-button>
        </div>
      </div>

      <a-row :gutter="16">
        <a-col :span="12">
          <vxe-grid id="BomManageLeft" ref="gridLeft" row-id="id" :columns="leftTableColumn"
            :toolbar-config="toolBarConfig" :custom-config="{}" :pager-config="{}" :loading="leftloading"
            :proxy-config="leftProxyConfig" min-height="202px">
            <!-- 工具栏 -->
            <template #toolbar_buttons>
              <a-space>
                <a-button type="primary" @click="openAddDialog()" :icon="h(PlusOutlined)">选择商品</a-button>
              </a-space>
            </template>
          </vxe-grid>
        </a-col>
        <a-col :span="12">
          <!-- 工具栏和切换按钮 -->
          <div class="right-header" role="tablist">
            <a-space>
              <a-radio-group v-model:value="activeTab" button-style="solid" @change="handleTabChange">
                <a-radio-button value="material">所需物料</a-radio-button>
                <a-radio-button value="process">生产工序</a-radio-button>
              </a-radio-group>
            </a-space>
          </div>

          <!-- 右侧表格 -->
          <vxe-grid id="BomManageRight" ref="gridRight" resizable show-overflow highlight-hover-row keep-source
            row-id="id" :loading="rightloading" :columns="currentColumns" :toolbar-config="toolBarConfig"
            :custom-config="{}" :pager-config="{}" :proxy-config="rightProxyConfig" min-height="202px"
            max-height="500px">
            <!-- 工具栏 -->
            <template #toolbar_buttons>
              <a-space>
                <a-button type="primary" @click="openAddDialog('material')" :icon="h(PlusOutlined)">
                  新增物料
                </a-button>
                <a-button type="primary" @click="openAddDialog('process')" :icon="h(PlusOutlined)">
                  新增工序
                </a-button>
              </a-space>
            </template>
            <!-- 操作列 -->
            <template #action_default="{ row }">
              <table-action outside :actions="createActions(row)" />
            </template>
          </vxe-grid>
        </a-col>
      </a-row>
      <!-- 新增物料弹窗 -->
      <AddMaterial ref="addMaterialDialog" @refresh="handleRefresh" />

      <!-- 新增工序弹窗 -->
      <AddProcess ref="addProcessDialog" @refresh="handleRefresh" />
    </page-wrapper>
  </div>
</template>

<script lang="ts">
import { defineComponent, h, ref, computed } from 'vue';
import { Modal } from 'ant-design-vue';
import { SearchOutlined, PlusOutlined, CheckOutlined, StopOutlined } from '@ant-design/icons-vue';
// import { message } from 'ant-design-vue';
import AddMaterial from './components/AddMaterial.vue';
import AddProcess from './components/AddProcess.vue';
import { bomProductApi } from '/@/api/base-data/product/bom-product';
import type { ColumnOptions } from 'vxe-table'
import type { VxeGridInstance } from 'vxe-table';
import type { MessageApi } from 'ant-design-vue/es/message';

interface SearchFormData {
  name: string;
  skuCode: string;
  available: any;
  productName?: string;
  barcode?: string;
}

interface ComponentInstance {
  $message: MessageApi;
  $utils: any;
  $refs: {
    gridLeft: VxeGridInstance;
    gridRight: VxeGridInstance;
    addMaterialDialog: any;
    addProcessDialog: any;
  };
}

export default defineComponent({
  name: 'BomManage',
  components: {
    AddMaterial,
    AddProcess,
  },
  setup() {
    const products = ref([]);

    // 获取商品数据
    const fetchProducts = async () => {
      try {
        const response = await bomProductApi.query();
        products.value = response.data;
      } catch (error) {
        console.error('Failed to fetch products:', error);
      }
    };

    // 计算属性，按创建时间倒序排列
    const sortedProducts = computed(() => {
      return [...products.value].sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
    });

    // 初始化时获取数据
    fetchProducts();

    return {
      h,
      SearchOutlined,
      PlusOutlined,
      CheckOutlined,
      StopOutlined,
      sortedProducts,
    };
  },
  data() {
    return {
      leftloading: false,
      rightloading: false,
      id: '',
      searchFormData: {
        name: '',
        skuCode: '',
        available: this.$enums?.AVAILABLE?.ENABLE?.code || '',
        productName: '',
        barcode: ''
      } as SearchFormData,
      goodsid: "",
      toolBarConfig: {
        slots: {
          buttons: 'toolbar_buttons',
        },
      },

      leftTableColumn: [
        { type: 'radio', width: 50 } as ColumnOptions,
        { field: 'code', title: '商品编号', width: 140 } as ColumnOptions,
        { field: 'name', title: '商品名称', minWidth: 140 } as ColumnOptions,
        { field: 'shortName', title: '商品简称', width: 140 } as ColumnOptions,
        { field: 'skuCode', title: 'SKU编号', width: 140 } as ColumnOptions,
        { field: 'categoryName', title: '分类', width: 140 } as ColumnOptions,
      ] as ColumnOptions[],

      activeTab: 'material', // 当前激活的标签页
      materialColumns: [
        { type: 'checkbox', width: 50 } as ColumnOptions,
        { title: '操作', width: 120, slots: { default: 'action_default' } } as ColumnOptions,
        { field: 'code', title: '商品编号', width: 120 } as ColumnOptions,
        { field: 'name', title: '商品名称', minWidth: 160 } as ColumnOptions,
        { field: 'purchasingPrice', title: '采购价格', width: 100 } as ColumnOptions,
        { field: 'skuCode', title: 'SKU编号', width: 100 } as ColumnOptions,
        { field: 'unit', title: '单位', width: 80 } as ColumnOptions,
        { field: 'quantity', title: '数量', width: 100 } as ColumnOptions,
      ] as ColumnOptions[],
      materialsProxyConfig: {
        props: {
          result: 'datas',
          total: 'totalCount',
        },
        ajax: {
          query: async ({ page, sorts }) => {
            try {
              if (!this.goodsid) {
                return {
                  datas: [],
                  totalCount: 0
                };
              }

              const params = {
                ...this.$utils.buildSortPageVo(page, sorts),
                id: this.goodsid,
              };

              console.log('Material Query Params:', params);

              const data = await bomProductApi.queryMaterialPage(params);
              console.log('Material Query Response:=========>', data);
              // 对数据进行排序，按添加时间正序排列
              data.datas.sort((a, b) => new Date(a.createTime) - new Date(b.createTime));
              return data;
            } catch (error) {
              console.error('Material Query Error:', error);
              return {
                datas: [],
                totalCount: 0
              };
            }
          },
        },
      },

      processColumns: [
        { type: 'checkbox', width: 50 } as ColumnOptions,
        { title: '操作', width: 120, slots: { default: 'action_default' } } as ColumnOptions,
        { field: 'executeProcesses', title: '执行顺序', width: 100 } as ColumnOptions,
        { field: 'processesName', title: '工序名称', minWidth: 160 } as ColumnOptions,
        { field: 'leader', title: '负责人员', width: 120 } as ColumnOptions,
        { field: 'billingMethod', title: '计费方式', width: 120 } as ColumnOptions,
        { field: 'wages', title: '工价', width: 100 } as ColumnOptions,
      ] as ColumnOptions[],

      processProxyConfig: {
        // 工序表的代理配置
        props: {
          result: 'datas',
          total: 'totalCount',
        },
        ajax: {
          query: async ({ page, sorts }) => {
            try {
              // 如果没有选择商品，直接返回空数据
              if (!this.goodsid) {
                return {
                  datas: [],
                  totalCount: 0
                };
              }
              const data = await bomProductApi.queryProcessPage({ ...this.buildQueryParams(page, sorts), productId: this.goodsid });
              // 过滤数据,筛选出选中商品的工序
              console.log('Process Query Response:=========>', data);
              data.datas.sort((b, a) => new Date(b.executeProcesses) - new Date(a.executeProcesses));

              return data;
            } catch (error) {
              console.error('API Error:', error);
              return {
                datas: [],
                totalCount: 0
              };
            }
          },
        },
      },

      leftProxyConfig: {
        props: {
          result: 'datas',
          total: 'totalCount',
        },
        ajax: {
          query: async ({ page, sorts }) => {
            try {
              const data = await bomProductApi.query(this.buildQueryParams(page, sorts));
              console.log('Original Data:', data.datas);
              // 对数据进行排序
              data.datas.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
              return data;
            } catch (error) {
              console.error('API Error:', error);
            }
          },
        },
      },
    };
  },
  computed: {
    // 根据当前标签返回对应的列配置
    currentColumns() {
      return this.activeTab === 'material' ? this.materialColumns : this.processColumns;
    },
    // 根据当前标签返回对应的数据
    rightProxyConfig() {
      return this.activeTab === 'material' ? this.materialsProxyConfig : this.processProxyConfig;
    },
  },
  methods: {
    // 添加处理标签切换的方法
    handleTabChange(value) {
      this.$nextTick(() => {
        this.loadTableData();
      });
    },

    // 加载右侧表格数据
    loadTableData() {
      this.rightloading = true;
      if (this.activeTab === 'material') {
        this.loadMaterialsData();
      } else {
        this.loadProcessesData();
      }
      this.rightloading = false;
    },
    // 查询右边物料列表，刷新
    loadMaterialsData() {
      (this.$refs.gridRight as VxeGridInstance)?.commitProxy?.('query');
    },
    // 查询右边工序列表，刷新
    loadProcessesData() {
      (this.$refs.gridRight as VxeGridInstance)?.commitProxy?.('query');
    },
    // 查询左边列表，刷新
    search() {
      (this.$refs.gridLeft as VxeGridInstance).commitProxy('reload');
    },

    // 查询左边列表，前构建查询参数结构
    buildQueryParams(page, sorts) {
      return {
        ...this.$utils.buildSortPageVo(page, sorts),
        ...this.buildSearchFormData(),
      };
    },
    // 查询右侧列表，前构建具体的查询参数
    buildSearchFormData() {
      return {
        ...this.searchFormData,
        // productId: this.goodsid,
      };
    },
    // 打开新增弹窗
    openAddDialog(type?: 'material' | 'process') {
      const selectedRecord = this.$refs.gridLeft.getRadioRecord();
      if (!selectedRecord) {
        this.$message.warning('请选择一个商品');
        return;
      }
      if (!type) {
        // 更新选中的商品信息
        this.searchFormData.productName = selectedRecord.name;
        this.searchFormData.barcode = selectedRecord.code;
        this.goodsid = selectedRecord.id;

        console.log('Selected Product:', selectedRecord);
        console.log('Set goodsid:', this.goodsid);

        this.$nextTick(() => {
          this.rightloading = true;
          try {
            this.loadTableData();
          } finally {
            this.rightloading = false;
          }
        });
        return;
      }

      // 如果是点击新增物料或工序按钮
      if (type === 'material') {
        if (!this.goodsid) {
          this.$message.warning('请先选择商品');
          return;
        }
        // 打开新增物料弹窗
        this.$refs.addMaterialDialog.openDialog(this.goodsid);
      } else if (type === 'process') {
        if (!this.goodsid) {
          this.$message.warning('请先选择商品');
          return;
        }
        // 打开新增工序弹窗
        this.$refs.addProcessDialog.openDialog(this.goodsid);
      }
    },
    // 创建操作按钮
    createActions(row) {
      return [
        {
          label: '编辑',
          onClick: () => {
            console.log("=============111111111111111111111111>row", row)
            if (this.activeTab === 'material') {
              this.$refs.addMaterialDialog.openDialog(this.goodsid, row);
            } else {
              this.$refs.addProcessDialog.openDialog(row);
            }
          },
        },
        {
          label: '删除',
          onClick: () => {
            Modal.confirm({
              title: this.activeTab === 'material'
                ? `确定要删除物料 "${row.name}" 吗？`
                : `确定要删除工序 "${row.processesName}" 吗？`,
              content: this.activeTab === 'material'
                ? '删除后将无法恢复该物料信息'
                : '删除后将无法恢复该工序信息',
              okText: '确定删除',
              cancelText: '取消',
              okButtonProps: {
                type: 'primary',
                danger: true
              },
              onOk: async () => {
                try {
                  await bomProductApi[
                    this.activeTab === 'material' ? 'deleteMaterial' : 'deleteProcesses'
                  ](row.id);
                  this.$message.success(
                    this.activeTab === 'material'
                      ? '物料删除成功'
                      : '工序删除成功'
                  );
                  this.loadTableData();
                } catch (error) {
                  this.$message.error(
                    this.activeTab === 'material'
                      ? '物料删除失败'
                      : '工序删除失败'
                  );
                }
              },
            });
          },
        },
      ];
    },
    // 处理刷新
    handleRefresh() {
      this.loadTableData();
    },
  },
});
</script>

<style lang="less" scoped>
.search-wrapper {
  position: relative;
  background-color: #fff;
  padding: 16px;
  margin-bottom: 10px;
  border-radius: 2px;

  :deep(.ant-form) {
    width: 250px;

    .ant-form-item {
      margin-bottom: 16px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }

  :deep(.j-form-item-container) {
    display: flex;
    flex-direction: column;
    align-items: stretch;
    padding: 5px;
  }

  .search-btn {
    position: absolute;
    right: 16px;
    bottom: 16px;
  }
}

.table-wrapper {
  background-color: #fff;
  padding: 16px;
  border-radius: 2px;
  overflow: hidden;
}

.vxe-grid {
  margin-bottom: 16px;
}

.toolbar {
  margin-bottom: 16px;
}

.tabs-wrapper {
  margin-bottom: 16px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.table-content {
  margin-top: 16px;
}

.right-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  background-color: #fff;
  border-radius: 4px;

  :deep(.ant-radio-group) {
    margin-right: 16px;
  }
}
</style>
